﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using TSqlServer;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
namespace FileManager
{
    /// <summary>
    /// FileSystemManager
    /// </summary>
    public class FileSystemManager :System.Web.UI.Page 
    {
        public static string userid="";
        private static string strRootFolder;
        
        static FileSystemManager()
        {
            strRootFolder = HttpContext.Current.Request.PhysicalApplicationPath;
            strRootFolder = strRootFolder.Substring(0, strRootFolder.LastIndexOf(@"\"));
            if (!Directory.Exists(strRootFolder + "\\users\\公共"))
                Directory.CreateDirectory(strRootFolder + "\\users\\公共");
            strRootFolder +="\\users\\" + HttpContext.Current.Session["userid"].ToString();
           

           
        }
        public static string GetDir(string path,int depth)
        {
            string dir = path.Replace(HttpContext.Current.Request.PhysicalApplicationPath+"users\\", "");
            string[] dirs = dir.Split('\\');
            if (dirs.Length > depth)
                return dirs[depth];
            else
                return "";

        }
        public static TSqlDBReader GetLLvUser()
        {
            string uid="";
            if(HttpContext.Current.Session["userid"]!=null)
                uid = HttpContext.Current.Session["userid"].ToString();
            TUser1 oUser=new TUser1(uid);
            oUser.Select();
            string sSql = " select userid from t_user1 where grpcode='" + oUser.GrpCode + "' and lvl<'" + oUser.Lvl + "'";
            TSqlDBReader myReader = new TSqlDBReader(sSql);
            return myReader;
        }

        /// <summary>
        /// 读根目录
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            return strRootFolder;
        }

        /// <summary>
        /// 写根目录
        /// </summary>
        /// <param name="path"></param>
        public static void SetRootPath(string path)
        {
            strRootFolder = path;
        }

        /// <summary>
        /// 读取列表
        /// </summary>
        /// <returns></returns>
        public static List<FileSystemItem> GetItems()
        {
            return GetItems(strRootFolder, DateTime.Now);
        }

        public static long DirSize(DirectoryInfo d)
        {
            long Size = 0;
            FileInfo[] fis = d.GetFiles();
            foreach (FileInfo fi in fis)
            {
                Size += fi.Length;
            }
            DirectoryInfo[] dis = d.GetDirectories();
            foreach (DirectoryInfo di in dis)
            {
                Size += DirSize(di);   
            }
            return (Size);
        }

        /// <summary>
        /// 读取列表
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<FileSystemItem> GetItems(string path,DateTime date)
        {
            string userdir = path.Replace(HttpContext.Current.Request.PhysicalApplicationPath + "users\\", "");
            if (userdir.IndexOf("\\") != -1)
                userdir = userdir.Substring(0, userdir.IndexOf("\\"));
            if (userdir != HttpContext.Current.Session["userid"].ToString() && path.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "").Split('\\').Length <= 3)
                if (path == HttpContext.Current.Request.PhysicalApplicationPath + "users")
                    path = GetRootPath();
                else if ((path.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "").Split('\\')).Length >=3 && userdir!="公共" )
                    path = GetRootPath() + "\\" + (path.Replace(HttpContext.Current.Request.PhysicalApplicationPath, "").Split('\\'))[2];
         
            
            string[] folders = Directory.GetDirectories(path);
            string[] files = Directory.GetFiles(path);
            List<FileSystemItem> list = new List<FileSystemItem>();
            string uid = HttpContext.Current.Session["userid"].ToString();

            TUser1 oUser=new TUser1(uid);
            oUser.Select();
            string sSql = " select userid from t_user1 where grpcode='" + oUser.GrpCode + "' and lvl<'" + oUser.Lvl + "'";
            TSqlDB db=new TSqlDB();
            db.OpenRset(sSql);
            DataView dv= db.DataSource;
            dv.Sort = "userid";

            if (path == GetRootPath())
            {
                FileSystemItem item = new FileSystemItem();
                DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath + "users\\公共");
                item.Name = "公共";
                item.Size = DirSize(di);
                item.FullName = di.FullName;
                item.IsFolder = true;
                list.Add(item);
            }
            foreach (string s in folders)
            {
                FileSystemItem item = new FileSystemItem();
                DirectoryInfo di = new DirectoryInfo(s);
                item.Name = di.Name;
                item.FullName = di.FullName;
                item.CreationDate = di.CreationTime;
                item.IsFolder = true;
                item.Size = DirSize(di);
                string did=GetDidByPath(item.FullName);
                if (item.Name.Split('_').Length >= 3)
                {
                    if (item.Name.Split('_')[0] == uid && (item.Name.Split('_')[1] != date.Year.ToString() || item.Name.Split('_')[2] != date.Month.ToString()))
                        continue;
                }
                if (did != "")
                {
                    TDir odir = new TDir(did);
                    odir.Select();
                    if (odir.Status == 1)
                        continue;
                    string userfolder=s.Replace(GetRootPath(),"");
                    if (userfolder.LastIndexOf("\\") != 0)
                        userfolder = userfolder.Substring(1, userfolder.IndexOf("\\",1)-1);
                    else
                        userfolder = userfolder.Substring(1);
               
                  
                }
                else
                {
                    TDir odir = new TDir();
                    odir.Id = Guid.NewGuid().ToString();
                    odir.Name = item.Name;
                    odir.Path = item.FullName;
                    odir.Status = 0;
                    odir.SortNum = 0;
                    odir.InMan = userid;
                    odir.InTime = DateTime.Now;
                    odir.Insert();
                }
                list.Add(item);
            }

            if (path.Substring(path.LastIndexOf("\\") + 1) == "被退回" || path.Substring(path.LastIndexOf("\\") + 1) == "提交审核" || path.Substring(path.LastIndexOf("\\") + 1) == "终稿")
            foreach (DataRow dr in dv.Table.Rows)
            {
                string fpath = GetRootPath().Substring(0, GetRootPath().LastIndexOf("\\")) + "\\" + dr["userid"].ToString() + "\\" + path.Substring(path.LastIndexOf("\\") + 1);
                if (!Directory.Exists(fpath))
                    continue;
                folders = Directory.GetDirectories(fpath);
                    foreach (string s in folders)
                    {
                        FileSystemItem item = new FileSystemItem();
                        DirectoryInfo di = new DirectoryInfo(s);
                        item.Name = di.Name;
                        item.FullName = di.FullName;
                        item.CreationDate = di.CreationTime;
                        item.IsFolder = true;
                        item.Size = DirSize(di);
                        string did = GetDidByPath(item.FullName);
                        if (item.Name.Split('_').Length >= 3)
                        {
                            if (item.Name.Split('_')[0] == dr["userid"].ToString() && (item.Name.Split('_')[1] != date.Year.ToString() || item.Name.Split('_')[2] != date.Month.ToString()))
                                continue;
                        }
                        if (did != "")
                        {
                            TDir odir = new TDir(did);
                            odir.Select();
                            if (odir.Status == 1)
                                continue;
                            string userfolder = s.Replace(GetRootPath(), "");
                            if (userfolder.LastIndexOf("\\") != 0)
                                userfolder = userfolder.Substring(1, userfolder.IndexOf("\\", 1) - 1);
                            else
                                userfolder = userfolder.Substring(1);
                 
                        }
                        else
                        {
                            TDir odir = new TDir();
                            odir.Id = Guid.NewGuid().ToString();
                            odir.Name = item.Name;
                            odir.Path = item.FullName;
                            odir.Status = 0;
                            odir.SortNum = 0;
                            odir.InMan = userid;
                            odir.InTime = DateTime.Now;
                            odir.Insert();
                        }
                        list.Add(item);
                    }
                
            }

           
            foreach (string s in files)
            {
                FileSystemItem item = new FileSystemItem();
                FileInfo fi = new FileInfo(s);
                item.Name = fi.Name;
                item.FullName = fi.FullName;
                item.CreationDate = fi.CreationTime;
                item.IsFolder = true;
                item.Size = fi.Length;
                string fid = GetFidByPath(item.FullName);
                if (fid != "")
                {
                    TFile ofile = new TFile(fid);
                    ofile.Select();
                    item.KeyWord = ofile.KeyWord;
                    if (ofile.Status == 1)
                        continue;
                    string userfolder = s.Replace(GetRootPath(), "");
                    if (userfolder.LastIndexOf("\\") != 0)
                        userfolder = userfolder.Substring(1, userfolder.IndexOf("\\", 1) - 1);
                    else
                        userfolder = userfolder.Substring(1);
                
                }
                else
                {
                    TFile ofile = new TFile();
                    if (FileSystemManager.GetFidByPath(path) == "")
                    {
                       
                        ofile.Id = Guid.NewGuid().ToString();
                        ofile.Name = item.Name;
                        ofile.Size = int.Parse ( item.Size.ToString());
                        ofile.KeyWord = "";
                        ofile.Remark = "";
                        ofile.Path = item.FullName;
                        ofile.Date = DateTime.Now;
                        ofile.Status = 0;
                        ofile.SortNum = 0;
                        ofile.InMan = userid;
                        ofile.InTime = DateTime.Now;
                        ofile.Insert();
                    }
                    TFileDir ofiledir = new TFileDir();
                    if (Path.GetDirectoryName(item.FullName ) != FileSystemManager.GetRootPath())
                    {
                        string did = FileSystemManager.GetDidByPath(Path.GetDirectoryName(item.FullName));
                        if (did != "")
                        {
                            ofiledir.DirId = did;
                            ofiledir.FileId = ofile.Id;
                            ofiledir.Status = 0;
                            ofiledir.SortNum = 0;
                            ofiledir.InMan = userid;
                            ofiledir.InTime = DateTime.Now;
                            ofiledir.Insert();

                        }
                    }
                }
                list.Add(item);
            }

            if (path.Substring(path.LastIndexOf("\\") + 1) == "被退回" || path.Substring(path.LastIndexOf("\\") + 1) == "提交审核" || path.Substring(path.LastIndexOf("\\") + 1) == "终稿")
                foreach (DataRow dr in dv.Table.Rows)
                {
                    string fpath = GetRootPath().Substring(0, GetRootPath().LastIndexOf("\\")) + "\\" + dr["userid"].ToString() + "\\" + path.Substring(path.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(fpath))
                        continue;
                    files = Directory.GetFiles(fpath);

                    foreach (string s in files)
                    {
                        FileSystemItem item = new FileSystemItem();
                        FileInfo fi = new FileInfo(s);
                        item.Name = fi.Name;
                        item.FullName = fi.FullName;
                        item.CreationDate = fi.CreationTime;
                        item.IsFolder = true;
                        item.Size = fi.Length;
                        string fid = GetFidByPath(item.FullName);
                        if (fid != "")
                        {
                            TFile ofile = new TFile(fid);
                            ofile.Select();
                            item.KeyWord = ofile.KeyWord;
                            if (ofile.Status == 1)
                                continue;
                            string userfolder = s.Replace(GetRootPath(), "");
                            if (userfolder.LastIndexOf("\\") != 0)
                                userfolder = userfolder.Substring(1, userfolder.IndexOf("\\", 1) - 1);
                            else
                                userfolder = userfolder.Substring(1);
                            //if (uid != userfolder && s.IndexOf(GetRootPath() + "\\公共") == -1)
                            //    if (dv.Find(userfolder) == -1)
                            //        continue;
                            //    else if (item.FullName.IndexOf(GetRootPath() + "\\" + userfolder + "\\" + "被退回") == -1 && item.FullName.IndexOf(GetRootPath() + "\\" + userfolder + "\\" + "提交审核") == -1 && item.FullName.IndexOf(GetRootPath() + "\\" + userfolder + "\\" + "终稿") == -1)
                            //        continue;
                        }
                        else
                        {
                            TFile ofile = new TFile();
                            if (FileSystemManager.GetFidByPath(path) == "")
                            {

                                ofile.Id = Guid.NewGuid().ToString();
                                ofile.Name = item.Name;
                                ofile.Size = int.Parse(item.Size.ToString());
                                ofile.KeyWord = "";
                                ofile.Remark = "";
                                ofile.Path = item.FullName;
                                ofile.Date = DateTime.Now;
                                ofile.Status = 0;
                                ofile.SortNum = 0;
                                ofile.InMan = userid;
                                ofile.InTime = DateTime.Now;
                                ofile.Insert();
                            }
                            TFileDir ofiledir = new TFileDir();
                            if (Path.GetDirectoryName(item.FullName) != FileSystemManager.GetRootPath())
                            {
                                string did = FileSystemManager.GetDidByPath(Path.GetDirectoryName(item.FullName));
                                if (did != "")
                                {
                                    ofiledir.DirId = did;
                                    ofiledir.FileId = ofile.Id;
                                    ofiledir.Status = 0;
                                    ofiledir.SortNum = 0;
                                    ofiledir.InMan = userid;
                                    ofiledir.InTime = DateTime.Now;
                                    ofiledir.Insert();

                                }
                            }
                        }
                        list.Add(item);
                    }


                }





            db.Free();

            if (path.ToLower() != strRootFolder.ToLower())
            {
                FileSystemItem topitem = new FileSystemItem();
                DirectoryInfo topdi = new DirectoryInfo(path).Parent;
                topitem.Name = "[上一级]";
                topitem.FullName = topdi.FullName;
                list.Insert(0, topitem);

                FileSystemItem rootitem = new FileSystemItem();
                DirectoryInfo rootdi = new DirectoryInfo(strRootFolder);
                rootitem.Name = "[根目录]";
                rootitem.FullName = rootdi.FullName;
                list.Insert(0, rootitem);

            }
            return list;
        }

        public static List<FileSystemItem> GetDeletedItems()
        {
            return GetDeletedItems(strRootFolder);
        }

        public static List<FileSystemItem> GetDeletedItems(string path)
        {
            string[] folders = Directory.GetDirectories(path);
            string[] files = Directory.GetFiles(path);
            List<FileSystemItem> list = new List<FileSystemItem>();
            string sSql = " select * from t_dir where status=1 and inman='" + HttpContext.Current.Session["userid"].ToString() + "' ";
            TSqlDBReader myreader = new TSqlDBReader(sSql);
            while (myreader.FDataReader.Read())
            {
                FileSystemItem item = new FileSystemItem();
                DirectoryInfo di = new DirectoryInfo(myreader.FDataReader["path"].ToString());
                if (di == null)
                    continue;
                item.Name = di.Name;
                item.FullName = di.FullName;
                item.CreationDate = di.CreationTime;
                item.IsFolder = true;
                item.Size = DirSize(di);
                list.Add(item);
            }
            myreader.Free();
            sSql = "select * from t_file where status=1 and inman='"+HttpContext.Current.Session["userid"].ToString()+"' ";
            myreader = new TSqlDBReader(sSql);
            while (myreader.FDataReader.Read())
            {
                FileSystemItem item = new FileSystemItem();
                FileInfo fi = new FileInfo(myreader.FDataReader["path"].ToString());
                if (!fi.Exists )
                    continue;
                item.Name = fi.Name;
                item.FullName = fi.FullName;
                item.CreationDate = fi.CreationTime;
                item.IsFolder = true;
                item.Size = fi.Length;
                string fid = GetFidByPath(item.FullName);
               
                list.Add(item);
            }
            myreader.Free();

            if (path.ToLower() != strRootFolder.ToLower())
            {
                FileSystemItem topitem = new FileSystemItem();
                DirectoryInfo topdi = new DirectoryInfo(path).Parent;
                topitem.Name = "[上一级]";
                topitem.FullName = topdi.FullName;
                list.Insert(0, topitem);

                FileSystemItem rootitem = new FileSystemItem();
                DirectoryInfo rootdi = new DirectoryInfo(strRootFolder);
                rootitem.Name = "[根目录]";
                rootitem.FullName = rootdi.FullName;
                list.Insert(0, rootitem);

            }
            return list;
        }

        /// <summary>
        /// 读取文件夹
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentName"></param>
        public static void CreateFolder(string name, string parentName)
        {
            DirectoryInfo di = new DirectoryInfo(parentName);
            di.CreateSubdirectory(name);
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path"></param>
        public static void _DeleteFolder(string path)
        {
            Directory.Delete(path);
        }

        /// <summary>
        /// 移动文件夹
        /// </summary>
        /// <param name="oldPath"></param>
        /// <param name="newPath"></param>
        public static void MoveFolder(string oldPath, string newPath)
        {
            newPath = newPath.Replace("\\" + GetDir(newPath, 0) + "\\", "\\" + GetDir(oldPath, 0) + "\\");
            _MoveDir(oldPath, newPath);
            Directory.Move(oldPath, newPath);
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="path"></param>
        public static void CreateFile(string filename, string path)
        {
            FileStream fs = File.Create(path + "\\" + filename);
            fs.Close();
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="path"></param>
        /// <param name="contents"></param>
        public static void CreateFile(string filename, string path, byte[] contents)
        {
            FileStream fs = File.Create(path + "\\" + filename);
            fs.Write(contents, 0, contents.Length);
            fs.Close();
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        public static void _DeleteFile(string path)
        {
            File.Delete(path);
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="oldPath"></param>
        /// <param name="newPath"></param>
        public static void _MoveFile(string oldPath, string newPath)
        {
            File.Move(oldPath, newPath);
        }

        /// <summary>
        /// 读取文件信息
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static FileSystemItem GetItemInfo(string path)
        {
            FileSystemItem item = new FileSystemItem();
            if (Directory.Exists(path))
            {
                DirectoryInfo di = new DirectoryInfo(path);
                item.Name = di.Name;
                item.FullName = di.FullName;
                item.CreationDate = di.CreationTime;
                item.IsFolder = true;
                item.LastAccessDate = di.LastAccessTime;
                item.LastWriteDate = di.LastWriteTime;
                item.FileCount = di.GetFiles().Length;
                item.SubFolderCount = di.GetDirectories().Length;
            }
            else
            {
                FileInfo fi = new FileInfo(path);
                item.Name = fi.Name;
                item.FullName = fi.FullName;
                item.CreationDate = fi.CreationTime;
                item.LastAccessDate = fi.LastAccessTime;
                item.LastWriteDate = fi.LastWriteTime;
                item.IsFolder = false;
                item.Size = fi.Length;
            }
            return item;
        }

        /// <summary>
        /// 复制文件夹
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        public static void CopyFolder(string source, string destination)
        {
            String[] files;
            
            if (source == destination)
                destination = destination.Insert(destination.LastIndexOf('\\') + 1, "复制 ");
            if (destination.IndexOf(source) == 0)
                return;
            if (destination[destination.Length - 1] != Path.DirectorySeparatorChar)
                destination += Path.DirectorySeparatorChar;

            destination = destination.Replace("\\" + GetDir(destination, 0) + "\\", "\\" + GetDir(source, 0) + "\\");
            if (!Directory.Exists(destination))
            {
                if (FileSystemManager.GetDidByPath(destination.TrimEnd('\\')) == "")
                {
                    TDir odir = new TDir();
                    odir.Id = Guid.NewGuid().ToString();
                    odir.Path = destination.TrimEnd('\\');
                    odir.Name = Path.GetFileName(odir.Path); 
                    odir.Status = 0;
                    odir.SortNum = 0;
                    odir.InMan = "";
                    odir.InTime = DateTime.Now;
                    odir.Insert();
                }
                Directory.CreateDirectory(destination);

            }
            files = Directory.GetFileSystemEntries(source);
            foreach (string element in files)
            {
                if (Directory.Exists(element))
                    CopyFolder(element, destination + Path.GetFileName(element));
                else
                {
                    File.Copy(element, destination + Path.GetFileName(element), true);
                }
            }
        }

        public static string GetDidByPath(string path)
        {
            string sSql = " select id from t_dir where path='" + path + "'";
            TSqlDBReader myReader = new TSqlDBReader(sSql);
            if (!myReader.FDataReader.HasRows)
                return "";
            myReader.FDataReader.Read();
            string id = myReader.FDataReader["id"].ToString();
            myReader.Free();
            return id;
        }

        public static string GetFidByPath(string path)
        {
            string sSql = " select id from t_file where path='" + path + "'";
            TSqlDBReader myReader = new TSqlDBReader(sSql);
            if (!myReader.FDataReader.HasRows)
                return "";
            myReader.FDataReader.Read();
            string id=myReader.FDataReader["id"].ToString();
            myReader.Free();
            return id;
        }
        public static void DeleteFolder(string path, bool isdel)
        {
            string did = GetDidByPath(path);
            if (did == "")
                return;
            if (isdel)
            {
                TSqlDB.ExecuteNonQuery(" delete from t_file where id in (select fileid from t_file_dir where dirid='" + did + "')");
                TSqlDB.ExecuteNonQuery(" delete from t_file_dir where dirid='" + did + "'");
                TSqlDB.ExecuteNonQuery(" delete from t_dir where id='" + did + "' ");
                _DeleteFolder(path);
            }
            else
            {
                //TSqlDB.ExecuteNonQuery(" update t_file set status='1' where id in (select fileid from t_file_dir where dirid='" + did + "')");
                //TSqlDB.ExecuteNonQuery(" update t_file_dir set status='1' where dirid='" + did + "'");
                TSqlDB.ExecuteNonQuery(" update t_dir set status='1' where id='" + did + "' ");
            }
        }
        

        public static void _MoveDir(string oldpath ,string newpath)
        {
            TSqlDB.ExecuteNonQuery(" update t_dir set Path =replace(path,'"+oldpath +"','"+ newpath+"') ");
            TSqlDB.ExecuteNonQuery(" update t_file set path = replace(path,'" + oldpath + "','" + newpath + "')");
        }
        public static void DeleteFile(string path, bool isdel)
        {
            string fid = GetFidByPath(path);

            if (isdel)
            {
                TSqlDB.ExecuteNonQuery(" delete from t_file where id ='" + fid + "'");
                TSqlDB.ExecuteNonQuery(" delete from t_file_dir where fileid='" + fid + "'");
                _DeleteFile(path);
            }
            else
            {
                TSqlDB.ExecuteNonQuery(" update t_file_dir set status='1' where fileid='" + fid + "'");
                TSqlDB.ExecuteNonQuery(" update t_file set status='1' where id='" + fid + "'");
                
            }
        }

        public static void MoveFile(string oldpath, string newpath)
        {
            newpath = newpath.Replace("\\" + GetDir(newpath, 0) + "\\", "\\" + GetDir(oldpath, 0) + "\\");
            TSqlDB.ExecuteNonQuery(" update t_file set path = replace(path,'" + oldpath + "','" + newpath + "')");
            _MoveFile(oldpath, newpath);
        }

        public static void RecoverFolder(string path)
        {
            string did = GetDidByPath(path);
            if (did == "")
                return;
        
            //TSqlDB.ExecuteNonQuery(" update t_file set status='0' where id in (select fileid from t_file_dir where dirid='" + did + "')");
            //TSqlDB.ExecuteNonQuery(" update t_file_dir set status='0' where dirid='" + did + "'");
            TSqlDB.ExecuteNonQuery(" update t_dir set status='0' where id='" + did + "' ");
            
        }

        public static void RecoverFile(string path)
        {
            string fid = GetFidByPath(path);
            //TSqlDB.ExecuteNonQuery(" update t_file_dir set status='0' where fileid='" + fid + "'");
            TSqlDB.ExecuteNonQuery(" update t_file set status='0' where id='" + fid + "'");
        }
    }
}